<template>
  <div>
    <h1>挂号表单</h1>
    <el-form :model="form" label-width="120px" ref="registrationForm">
      <!-- 患者信息 -->
      <h2>患者信息</h2>
      <el-form-item label="姓名" prop="realname">
        <el-input v-model="form.realname" placeholder="请输入姓名" required></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="form.gender" placeholder="请选择性别">
          <el-option 
            v-for="gender in genders" 
            :key="gender.id" 
            :label="gender.constantname" 
            :value="gender.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthdate">
        <el-date-picker
          v-model="form.birthdate"
          type="date"
          placeholder="请选择出生日期"
          required
          value-format="YYYY-MM-DD"
          @change="calculateAgeAndNoon"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="身份证号" prop="idnumber">
        <el-input v-model="form.idnumber" placeholder="请输入身份证号"></el-input>
      </el-form-item>
      <el-form-item label="家庭住址" prop="homeaddress">
        <el-input v-model="form.homeaddress" placeholder="请输入家庭住址"></el-input>
      </el-form-item>
      <el-form-item label="看诊日期" prop="visitdate">
        <el-date-picker
          v-model="form.visitdate"
          type="date"
          placeholder="请选择看诊日期"
          required
          value-format="YYYY-MM-DD"
          @change="calculateAgeAndNoon"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model="form.age" disabled></el-input>
      </el-form-item>
      <el-form-item label="午别" prop="noon">
        <el-input v-model="form.noon" disabled></el-input>
      </el-form-item>

      <!-- 挂号信息 -->
      <h2>挂号信息</h2>
      <el-form-item label="科室" prop="deptid">
        <el-select 
          v-model="form.deptid" 
          placeholder="请选择科室" 
          @change="onDeptChange"
          class="dept-selector"
        >
          <el-option 
            v-for="dept in departments" 
            :key="dept.id" 
            :label="dept.deptname" 
            :value="dept.id"
          >
            <span>{{ dept.deptname }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="医生" prop="userid">
        <el-select 
          v-model="form.userid" 
          placeholder="请选择医生"
          class="doctor-selector"
        >
          <el-option 
            v-for="doctor in doctors" 
            :key="doctor.id" 
            :label="doctor.realname" 
            :value="doctor.id"
          >
            <div class="doctor-option">
              <span class="doctor-name">{{ doctor.realname }}</span>
              <span class="doctor-dept">({{ doctor.deptname || '未分配科室' }})</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="挂号级别" prop="registleid">
        <el-select v-model="form.registleid" placeholder="请选择挂号级别" @change="calculateTotalFee">
          <el-option 
            v-for="level in registLevels" 
            :key="level.id" 
            :label="level.registname" 
            :value="level.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="病历本" prop="isbook">
        <el-checkbox v-model="form.isbook" @change="calculateTotalFee">是否购买病历本</el-checkbox>
      </el-form-item>
      <el-form-item label="总费用" prop="totalfee">
        <el-input v-model="form.totalfee" disabled></el-input>
      </el-form-item>
    </el-form>
    
    <!-- 支付弹窗 -->
    <el-dialog v-model="paymentDialogVisible" title="支付挂号费用" width="30%">
      <div class="payment-content">
        <div class="payment-info">
          <p><strong>挂号费用：</strong>¥{{ form.totalfee }}</p>
          <p><strong>患者姓名：</strong>{{ form.realname }}</p>
          <p><strong>就诊科室：</strong>{{ selectedDeptName }}</p>
          <p><strong>挂号医生：</strong>{{ selectedDoctorName }}</p>
        </div>
        <div class="payment-methods">
          <h4>选择支付方式：</h4>
          <el-radio-group v-model="paymentMethod">
            <el-radio label="wechat">微信支付</el-radio>
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="cash">现金支付</el-radio>
          </el-radio-group>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="paymentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPayment" :loading="paymentLoading">
            确认支付
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <el-button type="primary" @click="showPaymentDialog" :loading="loading" :disabled="!canSubmit">
      支付并提交挂号
    </el-button>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import service from '@/utils/request';

// 日期时间格式化函数
const formatDateTime = (date) => {
  const pad = num => num.toString().padStart(2, '0');
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
};

// 表单数据（完全匹配实体类字段名）
const form = ref({
  realname: '',
  gender: null,
  birthdate: null,
  idnumber: '',
  homeaddress: '',
  visitdate: null,
  age: null,
  agetype: '岁',
  noon: null,
  deptid: null,
  userid: null,
  registleid: null,
  settleid: 1, // 默认自费
  isbook: false,
  totalfee: 0,
  visitstate: 1 // 待就诊
});

// 支付相关状态
const paymentDialogVisible = ref(false);
const paymentMethod = ref('wechat');
const paymentLoading = ref(false);

// 加载状态
const loading = ref(false);
// 表单引用
const registrationForm = ref(null);

// 基础数据
const departments = ref([]);
const doctors = ref([]);
const registLevels = ref([]);
const genders = ref([]);

// 计算属性
const canSubmit = computed(() => {
  return form.value.realname && 
         form.value.gender && 
         form.value.birthdate && 
         form.value.visitdate && 
         form.value.deptid && 
         form.value.userid && 
         form.value.registleid &&
         form.value.totalfee > 0;
});

const selectedDeptName = computed(() => {
  return departments.value.find(d => d.id === form.value.deptid)?.deptname || '';
});

const selectedDoctorName = computed(() => {
  return doctors.value.find(d => d.id === form.value.userid)?.realname || '';
});

// 调试函数：打印API响应结构
const logApiResponse = (response, apiName) => {
  console.log(`[API响应] ${apiName}:`, response);
  
  // 检查常见结构
  if (response && response.data) {
    console.log(`[API响应] ${apiName} 包含data字段:`, response.data);
  }
  
  if (response && response.success !== undefined) {
    console.log(`[API响应] ${apiName} 包含success字段:`, response.success);
  }
};

// 处理API响应的帮助函数
const handleApiResponse = (response, apiName) => {
  logApiResponse(response, apiName);
  
  // 尝试几种常见的响应结构
  try {
    // 情况1: 直接返回数据数组
    if (Array.isArray(response)) {
      return response;
    }
    
    // 情况2: { success: true, data: [...] }
    if (response && response.success && response.data) {
      return response.data;
    }
    
    // 情况3: { code: 200, data: [...] }
    if (response && response.code === 200 && response.data) {
      return response.data;
    }
    
    // 情况4: { data: [...] }
    if (response && response.data) {
      return response.data;
    }
    
    // 情况5: 直接返回对象
    return response;
  } catch (error) {
    console.error(`[API解析错误] ${apiName}:`, error);
    throw new Error(`API响应格式不正确: ${apiName}`);
  }
};

// 加载基础数据
const loadData = async () => {
  try {
    // 获取科室列表
    const deptResponse = await service.get('/register/departments');
    const deptData = handleApiResponse(deptResponse, 'departments');
    departments.value = deptData.departments || deptData || [];
    
    // 获取挂号级别列表
    const levelResponse = await service.get('/register/registLevels');
    const levelData = handleApiResponse(levelResponse, 'registLevels');
    registLevels.value = levelData || [];
    
    // 获取性别选项列表
    const genderResponse = await service.get('/register/genders');
    const genderData = handleApiResponse(genderResponse, 'genders');
    genders.value = genderData || [];
    
    console.log('基础数据加载完成:', {
      departments: departments.value.length,
      registLevels: registLevels.value.length,
      genders: genders.value.length
    });
    
    if (!departments.value.length) {
      throw new Error('科室数据为空');
    }
    
    if (!registLevels.value.length) {
      throw new Error('挂号级别数据为空');
    }
    
    if (!genders.value.length) {
      throw new Error('性别数据为空');
    }
    
    ElMessage.success('基础数据加载成功');
  } catch (error) {
    console.error('加载基础数据失败:', error);
    ElMessage.error('加载基础数据失败: ' + (error.message || '未知错误'));
  }
};

// 根据科室ID获取医生列表
const getDoctorsByDeptId = async (deptId) => {
  try {
    const response = await service.get(`/register/doctors/${deptId}`);
    const data = handleApiResponse(response, `doctors/${deptId}`);
    
    doctors.value = (data.doctors || data || []).map(doctor => ({
      ...doctor,
      deptname: departments.value.find(d => d.id === deptId)?.deptname || '未分配科室'
    }));
  } catch (error) {
    console.error('获取医生列表失败:', error);
    ElMessage.error('获取医生列表失败: ' + (error.message || '未知错误'));
  }
};

// 科室选择改变事件
const onDeptChange = (deptId) => {
  form.value.userid = null; // 重置医生选择
  if (deptId) {
    getDoctorsByDeptId(deptId);
  } else {
    doctors.value = [];
  }
};

// 计算年龄
const calculateAge = (birthDate, visitDate) => {
  if (!birthDate || !visitDate) return null;
  
  const birth = new Date(birthDate);
  const visit = new Date(visitDate);
  
  let age = visit.getFullYear() - birth.getFullYear();
  const monthDiff = visit.getMonth() - birth.getMonth();
  
  if (monthDiff < 0 || (monthDiff === 0 && visit.getDate() < birth.getDate())) {
    age--;
  }
  return age;
};

// 计算午别
const calculateNoon = () => {
  const now = new Date();
  return now.getHours() < 12 ? '上午' : '下午';
};

// 计算年龄和午别
const calculateAgeAndNoon = () => {
  if (form.value.birthdate && form.value.visitdate) {
    form.value.age = calculateAge(form.value.birthdate, form.value.visitdate);
  }
  form.value.noon = calculateNoon();
};

// 计算总费用
const calculateTotalFee = async () => {
  if (!form.value.registleid) return;
  
  try {
    const response = await service.get('/register/calculateFee', {
      params: {
        registLevelId: form.value.registleid,
        isBook: form.value.isbook
      }
    });
    const data = handleApiResponse(response, 'calculateFee');
    form.value.totalfee = data.totalFee || 0;
  } catch (error) {
    console.error('计算总费用失败:', error);
    ElMessage.error('计算总费用失败: ' + (error.message || '未知错误'));
  }
};

// 显示支付对话框
const showPaymentDialog = async () => {
  try {
    // 验证表单
    await registrationForm.value.validate();
    
    // 检查总费用
    if (form.value.totalfee <= 0) {
      ElMessage.warning('请先计算总费用');
      return;
    }
    
    // 显示支付对话框
    paymentDialogVisible.value = true;
  } catch (error) {
    console.error('表单验证失败:', error);
    ElMessage.error('请完善所有必填信息');
  }
};

// 确认支付
const confirmPayment = async () => {
  paymentLoading.value = true;
  try {
    // 模拟支付过程
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    // 支付成功后提交表单
    await submitForm();
    
    // 关闭支付对话框
    paymentDialogVisible.value = false;
  } catch (error) {
    console.error('支付失败:', error);
    ElMessage.error('支付失败: ' + (error.message || '未知错误'));
  } finally {
    paymentLoading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  try {
    loading.value = true;
    
    // 构建请求数据
    const requestData = {
      realname: form.value.realname,
      gender: form.value.gender,
      birthdate: form.value.birthdate,
      idnumber: form.value.idnumber || null,
      homeaddress: form.value.homeaddress || null,
      visitdate: form.value.visitdate,
      age: form.value.age,
      agetype: '岁',
      noon: form.value.noon,
      deptid: form.value.deptid,
      userid: form.value.userid,
      registleid: form.value.registleid,
      settleid: 1,
      isbook: form.value.isbook ? '是' : '否',
      registerid: 1, // 实际应为登录用户ID
      visitstate: 1,
      paymentMethod: paymentMethod.value,
      paymentAmount: form.value.totalfee
    };

    const response = await service.post('/register/save', requestData);
    const data = handleApiResponse(response, 'save');
    
    if (data.success) {
      ElMessage.success(`挂号成功，病历号：${data.caseNumber}`);
      // 重置表单
      resetForm();
    } else {
      ElMessage.error(data.message || '挂号失败');
    }
  } catch (error) {
    console.error('提交失败:', error);
    if (error.name !== 'AxiosError') {
      ElMessage.error('表单验证失败: ' + error.message);
    } else {
      ElMessage.error('挂号请求失败: ' + (error.response?.data?.message || error.message));
    }
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  if (registrationForm.value) {
    registrationForm.value.resetFields();
  }
  form.value = {
    realname: '',
    gender: null,
    birthdate: null,
    idnumber: '',
    homeaddress: '',
    visitdate: null,
    age: null,
    agetype: '岁',
    noon: null,
    deptid: null,
    userid: null,
    registleid: null,
    settleid: 1,
    isbook: false,
    totalfee: 0,
    visitstate: 1
  };
  doctors.value = [];
};

// 组件挂载时加载数据
onMounted(() => {
  loadData();
});
</script>

<style scoped>
h1 {
  font-size: 24px;
  margin-bottom: 20px;
}

.dept-selector, .doctor-selector {
  width: 100%;
}

.doctor-option {
  display: flex;
  justify-content: space-between;
}

.doctor-name {
  font-weight: bold;
}

.doctor-dept {
  color: #909399;
  font-size: 12px;
}

.payment-content {
  padding: 10px;
}

.payment-info {
  margin-bottom: 20px;
  line-height: 1.8;
}

.payment-methods {
  margin-top: 20px;
}

.payment-methods h4 {
  margin-bottom: 10px;
}
</style>